package com.android.UrbanRemix;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

import com.android.UrbanRemix.Request;
import com.android.UrbanRemix.WavIO;
import com.android.UrbanRemix.HttpFileUploader;
import com.android.UrbanRemix.UrbanRemix_New;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class PostSnapShot extends Activity {
	Button saveSnapShotButton, discardSnapShotButton, skipSnapShotButton,
			recordButton, quitButton, stopButton;
	Button takeSnapShotButton, uploadNowButton, recordAnotherButton,
			reviewUploadQueueButton;
	Button playButton, saveSoundButton, discardSoundButton;
	// ------------
	// vars for GPS...
	LocationManager locationManager;
	double lat, lng, acc;

	// ------------
	// ...for network i/o
	String username;
	String password;
	String muploadUrlString;
	String tags;
	String taggedFileName;
	public static final String TAGS_XML = "http://urbanremix.lcc.gatech.edu/tags_xml.php";
	public static final String MUPLOAD = "http://urbanremix.lcc.gatech.edu/mupload.php";
	HttpFileUploader qUploader;
	Request rq;
	public int testvar;

	// ------------
	// ...for recording
	Thread recordingthread;
	WavIO wavio;
	CameraPreview cp;
	ImageCaptureCallback iccb;

	private MediaPlayer mp;
	private String externalMediaPath, localAudioPath;
	boolean recording = false;
	boolean recorded = false;
	boolean playing = false;
	private File rawFileName, wavFileName;
	private String folderPath, tempFolderPath, queueFolderPath,
			userChoiceFolderPath;
	private File folder, tempFolder, queueFolder, userChoiceFolder;

	static final int CHOOSE_TAGS_REQUEST = 0;
	static final int SNAPSHOT_REQUEST = 1;
	Context myContext;

	// -------------
	// ...for saving preferences on exit / on load
	public static final String MYPREFS = "mySharedPreferences";

	public int flag;
	public String wavname;
	public String wavnameanddate;

	// public String location_context;
	public void onCreate(Bundle savedInstanceState) {

		// Bundle b = this.getIntent().getExtras();

		lat = lng = acc = 0.0;

		// -----------
		// get the current location if available
		String location_context = Context.LOCATION_SERVICE;
		locationManager = (LocationManager) getSystemService(location_context);
		testProviders();

		externalMediaPath = Environment.getExternalStorageDirectory()
				.getAbsolutePath();

		folderPath = externalMediaPath + "/urbanremix";
		tempFolderPath = folderPath + "/temp";
		queueFolderPath = folderPath + "/queue";
		userChoiceFolderPath = folderPath + "/userchoice";

		queueFolder = new File(queueFolderPath);
		folder = new File(folderPath);
		tempFolder = new File(tempFolderPath);
		userChoiceFolder = new File(userChoiceFolderPath);

		if (!folder.exists())
			folder.mkdir();
		if (!tempFolder.exists())
			tempFolder.mkdir();
		if (!queueFolder.exists())
			queueFolder.mkdir();
		if (!userChoiceFolder.exists())
			userChoiceFolder.mkdir();

		File[] tempfiles;
		tempfiles = tempFolder.listFiles();
		int t = tempfiles.length;
		// ((android.widget.Button)findViewById(R.id.Start)).setText(h);
		int i = 0;
		while (i < t) {
			tempfiles[i].delete();
			i++;
		}

		rq = new Request();
		myContext = this;
		// qUploader = new HttpFileUploader(this, PostSnapShot.MUPLOAD);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.postsnapshot);

		saveSnapShotButton = (Button) findViewById(R.id.SaveSnapshot);
		discardSnapShotButton = (Button) findViewById(R.id.DiscardSnapshot);
		takeSnapShotButton = (Button) findViewById(R.id.TakeSnapshot);
		skipSnapShotButton = (Button) findViewById(R.id.SkipSnapshot);
		uploadNowButton = (Button) findViewById(R.id.UploadNow);
		reviewUploadQueueButton = (Button) findViewById(R.id.Review);
		recordAnotherButton = (Button) findViewById(R.id.RecordAnother);
		recordButton = (Button) findViewById(R.id.Record);
		quitButton = (Button) findViewById(R.id.Quit);
		stopButton = (Button) findViewById(R.id.Stop);
		playButton = (Button) findViewById(R.id.Play);
		saveSoundButton = (Button) findViewById(R.id.Save);
		discardSoundButton = (Button) findViewById(R.id.Discard);

		recordButton.setVisibility(View.VISIBLE);
		quitButton.setVisibility(View.VISIBLE);
		takeSnapShotButton.setVisibility(View.VISIBLE);
		reviewUploadQueueButton.setVisibility(View.VISIBLE);
		stopButton.setVisibility(View.GONE);
		uploadNowButton.setVisibility(View.GONE);
		recordAnotherButton.setVisibility(View.GONE);

		saveSnapShotButton.setVisibility(View.GONE);
		discardSnapShotButton.setVisibility(View.GONE);

		skipSnapShotButton.setVisibility(View.GONE);
		playButton.setVisibility(View.GONE);
		saveSoundButton.setVisibility(View.GONE);
		discardSoundButton.setVisibility(View.GONE);

		// stopButton.setEnabled(false);

		wavio = new WavIO(this, "SoundRecording");
		wavio.setFrequency(44100);
		wavio.setChannelConfiguration(AudioFormat.CHANNEL_CONFIGURATION_MONO);

		recordButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				((android.widget.Button) findViewById(R.id.Record))
						.setEnabled(false);
				((android.widget.Button) findViewById(R.id.Review))
						.setEnabled(false);
				((android.widget.Button) findViewById(R.id.TakeSnapshot))
						.setEnabled(false);
				((android.widget.Button) findViewById(R.id.Quit))
						.setEnabled(false);
				((android.widget.Button) findViewById(R.id.Stop))
						.setVisibility(View.VISIBLE);
				recordingthread = new Thread(null, wavio, "Recording");
				recordingthread.start();
				wavio.setRecording(true);
				stopButton.setEnabled(true);

			}
		});

		stopButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				wavio.setRecording(false);

				((android.widget.Button) findViewById(R.id.Quit))
						.setEnabled(true);
				recordButton.setVisibility(View.GONE);
				quitButton.setVisibility(View.GONE);
				stopButton.setVisibility(View.GONE);
				reviewUploadQueueButton.setVisibility(View.GONE);
				uploadNowButton.setVisibility(View.GONE);
				recordAnotherButton.setVisibility(View.GONE);

				saveSnapShotButton.setVisibility(View.GONE);
				discardSnapShotButton.setVisibility(View.GONE);
				takeSnapShotButton.setVisibility(View.GONE);
				skipSnapShotButton.setVisibility(View.GONE);
				playButton.setVisibility(View.VISIBLE);
				saveSoundButton.setVisibility(View.VISIBLE);
				discardSoundButton.setVisibility(View.VISIBLE);

			}
		});

		playButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (!playing) {
					try {
						// set the button text
						// Request.notification( myContext ,"Playing sound",
						// "Recently recorded "+wavio.getWavFileName());
						((android.widget.Button) findViewById(R.id.Play))
								.setText(R.string.stop);
						startPlayback();
						playing = true;

					} catch (IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalStateException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					// set the button text

					((android.widget.Button) findViewById(R.id.Play))
							.setText(R.string.play);
					stopPlayback();
					// Request.notification( myContext ,"Stopped playing",
					// "Recently recorded "+wavio.getWavFileName());
					playing = false;
				}
			}
		});

		saveSoundButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				// Request.notification( myContext ,"Audio",
				// "Audio Stored: "+wavio.getWavFileName());
				// myContext.toggleButtonAvailability(true);
				saveSoundFunctionality();
				((android.widget.Button) findViewById(R.id.Record))
						.setEnabled(true);
				((android.widget.Button) findViewById(R.id.Review))
						.setEnabled(true);
				((android.widget.Button) findViewById(R.id.TakeSnapshot))
						.setEnabled(true);
				((android.widget.Button) findViewById(R.id.Quit))
						.setEnabled(true);

			}
		});

		takeSnapShotButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				Intent intent = new Intent(myContext, CameraPreview.class);
				intent.putExtra("tempFolderPath", getTempFolderPath());
				startActivity(intent);
				saveSnapShotButton.setVisibility(View.VISIBLE);
				discardSnapShotButton.setVisibility(View.VISIBLE);
				takeSnapShotButton.setVisibility(View.GONE);
				skipSnapShotButton.setVisibility(View.GONE);
				reviewUploadQueueButton.setVisibility(View.GONE);
				recordButton.setVisibility(View.GONE);
				quitButton.setVisibility(View.GONE);

			}

		});

		saveSnapShotButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				savesnapshot_functionality();
			}

		});

		discardSoundButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				File[] tempfiles_toDiscard = tempFolder.listFiles();
				int t = tempfiles_toDiscard.length;
				// ((android.widget.Button)findViewById(R.id.Start)).setText(h);
				int i = 0;
				while (i < t) {

					String temp = tempfiles_toDiscard[i].getName();
					String ext_todiscard = temp.substring(
							temp.lastIndexOf(".") + 1, temp.length());
					if (ext_todiscard.equals(new String("wav"))) {
						Request.notification(myContext, "Audio",
								"Audio Discarded:" + temp);
						tempfiles_toDiscard[i].delete();

					}

					i++;
				}

				recordButton.setVisibility(View.VISIBLE);
				quitButton.setVisibility(View.VISIBLE);
				takeSnapShotButton.setVisibility(View.VISIBLE);
				reviewUploadQueueButton.setVisibility(View.VISIBLE);
				stopButton.setVisibility(View.GONE);
				uploadNowButton.setVisibility(View.GONE);
				recordAnotherButton.setVisibility(View.GONE);
				saveSnapShotButton.setVisibility(View.GONE);
				discardSnapShotButton.setVisibility(View.GONE);
				skipSnapShotButton.setVisibility(View.GONE);
				playButton.setVisibility(View.GONE);
				saveSoundButton.setVisibility(View.GONE);
				discardSoundButton.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.Record))
						.setEnabled(true);
				((android.widget.Button) findViewById(R.id.Review))
						.setEnabled(true);
				((android.widget.Button) findViewById(R.id.TakeSnapshot))
						.setEnabled(true);
				((android.widget.Button) findViewById(R.id.Quit))
						.setEnabled(true);
			}

		});

		discardSnapShotButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				File[] tempfiles_toDiscard = tempFolder.listFiles();
				int t = tempfiles_toDiscard.length;
				// ((android.widget.Button)findViewById(R.id.Start)).setText(h);
				int i = 0;
				while (i < t) {

					String temp = tempfiles_toDiscard[i].getName();
					String ext_todiscard = temp.substring(
							temp.lastIndexOf(".") + 1, temp.length());
					if (ext_todiscard.equals(new String("jpg"))) {
						Request.notification(myContext, "Image",
								"Snapshot Discarded:" + temp);
						tempfiles_toDiscard[i].delete();

					}

					i++;
				}
				recordButton.setVisibility(View.VISIBLE);
				quitButton.setVisibility(View.VISIBLE);
				takeSnapShotButton.setVisibility(View.VISIBLE);
				reviewUploadQueueButton.setVisibility(View.VISIBLE);

				stopButton.setVisibility(View.GONE);
				uploadNowButton.setVisibility(View.GONE);
				recordAnotherButton.setVisibility(View.GONE);

				saveSnapShotButton.setVisibility(View.GONE);
				discardSnapShotButton.setVisibility(View.GONE);

				skipSnapShotButton.setVisibility(View.GONE);
				playButton.setVisibility(View.GONE);
				saveSoundButton.setVisibility(View.GONE);
				discardSoundButton.setVisibility(View.GONE);

			}

		});

		reviewUploadQueueButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				File[] userChoiceFiles = userChoiceFolder.listFiles();
				int t = userChoiceFiles.length;
				if (t <= 0) {
					Request.notification(myContext, "Error",
							"No files to display");
				} else {
					Intent intent = new Intent(myContext,
							UploadFunctionality.class);
					startActivity(intent);
				}
			}

		});

		quitButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent(myContext, ExitScreen.class);

				startActivity(intent);

				recordButton.setVisibility(View.GONE);
				quitButton.setVisibility(View.GONE);
				stopButton.setVisibility(View.GONE);
				uploadNowButton.setVisibility(View.VISIBLE);
				recordAnotherButton.setVisibility(View.VISIBLE);
				saveSnapShotButton.setVisibility(View.GONE);
				discardSnapShotButton.setVisibility(View.GONE);
				takeSnapShotButton.setVisibility(View.GONE);
				skipSnapShotButton.setVisibility(View.GONE);
				playButton.setVisibility(View.GONE);
				saveSoundButton.setVisibility(View.GONE);
				discardSoundButton.setVisibility(View.GONE);

			}
		});

		uploadNowButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// File[] tempfilesInQueue = queueFolder.listFiles();
				// int t=tempfilesInQueue.length;
				// ((android.widget.Button)findViewById(R.id.Start)).setText(h);
				// if(t>0)
				// {
				upload_functionality();
				// }
				// else
				// {
				// Request.notification( myContext ,"Message",
				// "Sorry. No files to upload" );
				// }
				uploadNowButton.setVisibility(View.GONE);
				recordAnotherButton.setVisibility(View.VISIBLE);

				saveSnapShotButton.setVisibility(View.GONE);
				discardSnapShotButton.setVisibility(View.GONE);
				takeSnapShotButton.setVisibility(View.GONE);
				skipSnapShotButton.setVisibility(View.GONE);
				playButton.setVisibility(View.GONE);
				saveSoundButton.setVisibility(View.GONE);
				discardSoundButton.setVisibility(View.GONE);
				recordButton.setVisibility(View.GONE);
				quitButton.setVisibility(View.VISIBLE);
				stopButton.setVisibility(View.GONE);
			}

		});

		recordAnotherButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				recordButton.setVisibility(View.VISIBLE);
				quitButton.setVisibility(View.VISIBLE);
				stopButton.setVisibility(View.VISIBLE);
				recordButton.setVisibility(View.VISIBLE);
				quitButton.setVisibility(View.VISIBLE);
				stopButton.setEnabled(false);
				recordButton.setEnabled(true);
				uploadNowButton.setVisibility(View.GONE);
				recordAnotherButton.setVisibility(View.GONE);

				saveSnapShotButton.setVisibility(View.GONE);
				discardSnapShotButton.setVisibility(View.GONE);
				takeSnapShotButton.setVisibility(View.GONE);
				skipSnapShotButton.setVisibility(View.GONE);
				playButton.setVisibility(View.GONE);
				saveSoundButton.setVisibility(View.GONE);
				discardSoundButton.setVisibility(View.GONE);

			}
		});

		skipSnapShotButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				recordButton.setVisibility(View.GONE);
				quitButton.setVisibility(View.VISIBLE);
				stopButton.setVisibility(View.GONE);
				recordButton.setVisibility(View.GONE);
				quitButton.setVisibility(View.GONE);
				uploadNowButton.setVisibility(View.VISIBLE);
				recordAnotherButton.setVisibility(View.VISIBLE);

				saveSnapShotButton.setVisibility(View.GONE);
				discardSnapShotButton.setVisibility(View.GONE);
				takeSnapShotButton.setVisibility(View.GONE);
				skipSnapShotButton.setVisibility(View.GONE);
				playButton.setVisibility(View.GONE);
				saveSoundButton.setVisibility(View.GONE);
				discardSoundButton.setVisibility(View.GONE);
				skip_snapshot_functionality();

			}
		});

	}

	public void startPlayback() // throws IllegalArgumentException,
	// IllegalStateException, IOException
	{

		try {
			mp = new MediaPlayer();
			mp.setDataSource(wavio.getWavFileName());
			// Request.notification( myContext ,"Playing sound",
			// wavio.getWavFileName());
			mp.prepare();
			mp.start();
			mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

				public void onCompletion(MediaPlayer mp) {
					((android.widget.Button) findViewById(R.id.Play))
							.setText(R.string.play);
					playing = false;
				}
			});
		} catch (Exception e) {
			Request.notification(this, "error", e.getMessage());
		}
	}

	public void stopPlayback() {
		mp.stop();
		mp.release();
	}

	public void saveSoundFunctionality() {

		((android.widget.Button) findViewById(R.id.TakeSnapshot))
				.setVisibility(View.VISIBLE);
		((android.widget.Button) findViewById(R.id.Quit))
				.setVisibility(View.VISIBLE);
		((android.widget.Button) findViewById(R.id.Review))
				.setVisibility(View.VISIBLE);
		((android.widget.Button) findViewById(R.id.Record))
				.setVisibility(View.VISIBLE);
		((android.widget.Button) findViewById(R.id.RecordAnother))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.SaveSnapshot))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.DiscardSnapshot))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.SkipSnapshot))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.UploadNow))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.Stop))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.Play))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.Save))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.Discard))
				.setVisibility(View.GONE);

		taggedFileName = wavio.getBaseFileNameAndCurrentDate();

		testProviders();
		Double latDouble = (Double) lat;
		String latString = latDouble.toString();
		Double lngDouble = (Double) lng;
		String lngString = lngDouble.toString();
		Double accDouble = (Double) acc;
		String accString = accDouble.toString();

		registerFilePrefs(taggedFileName, latString, lngString, accString, tags);
		// Request.notification( myContext
		// ,"hello","File:"+taggedFileName+"lat"+latString+"long"+lngString+"acc"+accString);
		tempToUserChoice();
		// tempToQueue();

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// ------------
		// When the TagSelection activity has terminated, get its return
		// message.

		if (requestCode == CHOOSE_TAGS_REQUEST) {
			Bundle b;
			try {
				b = data.getExtras();

				String returnMessage = b
						.getString("com.android.urbanremix.ReturnMessage");
				TextView tv = (TextView) findViewById(R.id.statusbar);
				// Request.notification( myContext ,"Message",returnMessage);
				// tv.setTextColor(11);
				tv.setVisibility(1);
				tv.setText(returnMessage);

			} catch (NullPointerException e) {
			}

			// ------------
			// if the TagSelection's return message is "OK" (i.e., the user hit
			// the "upload"
			// button), then we assume we've been passed a comma-separated
			// string of tags.
			// we then try to get the most current location, save the info
			// related to this file
			// in our saved preferences (which will persist even if the app is
			// terminated),
			// copy the temporary files -- wav and jpg alike -- into the queue
			// for uploading,
			// start the uploader thread (if it hasn't started already), and
			// reset the state
			// of the buttons.

			switch (resultCode) {
			case RESULT_OK:
				b = data.getExtras();

				((android.widget.Button) findViewById(R.id.UploadNow))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.RecordAnother))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.SaveSnapshot))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.TakeSnapshot))
						.setVisibility(View.VISIBLE);
				((android.widget.Button) findViewById(R.id.DiscardSnapshot))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.SkipSnapshot))
						.setVisibility(View.VISIBLE);
				((android.widget.Button) findViewById(R.id.Quit))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.Record))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.Stop))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.Play))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.Save))
						.setVisibility(View.GONE);
				((android.widget.Button) findViewById(R.id.Discard))
						.setVisibility(View.GONE);

				tags = b.getString("com.android.urbanremix.Tags");
				int mode = Activity.MODE_PRIVATE;
				SharedPreferences mySharedPreferences = getSharedPreferences(
						"mySharedPreferences", mode);
				taggedFileName = wavio.getBaseFileNameAndCurrentDate();

				testProviders();
				Double latDouble = (Double) lat;
				String latString = latDouble.toString();
				Double lngDouble = (Double) lng;
				String lngString = lngDouble.toString();
				Double accDouble = (Double) acc;
				String accString = accDouble.toString();

				registerFilePrefs(taggedFileName, latString, lngString,
						accString, tags);
				// Request.notification( myContext
				// ,"hello","File:"+taggedFileName+"lat"+latString+"long"+lngString+"acc"+accString);
				// tempToQueue();

				break;

			case RESULT_CANCELED:
				TextView tv = (TextView) findViewById(R.id.statusbar);

				try {
					b = data.getExtras();
					String returnMessage = b
							.getString("com.android.urbanremix.ReturnMessage");
					// Request.notification( myContext
					// ,"Message",returnMessage);
					tv.setText(returnMessage);
				}
				// if the cancellation didn't return an error message -- e.g.,
				// if the user
				// just clicked the back button on the phone -- then don't
				// display anything in
				// the status bar.
				catch (NullPointerException e) {
				}

			default:
				break;
			}
		}
	}

	public void skip_snapshot_functionality() {
		File[] tempfiles_toDiscard = tempFolder.listFiles();
		int t = tempfiles_toDiscard.length;
		// ((android.widget.Button)findViewById(R.id.Start)).setText(h);
		int i = 0;
		while (i < t) {

			String temp = tempfiles_toDiscard[i].getName();
			String ext_todiscard = temp.substring(temp.lastIndexOf(".") + 1,
					temp.length());
			if (ext_todiscard.equals(new String("jpg"))) {
				Request.notification(myContext, "Image", "Snapshot Discarded:"
						+ temp);
				tempfiles_toDiscard[i].delete();

			}

			i++;
		}
		tempToQueue();

	}

	public void savesnapshot_functionality() {

		((android.widget.Button) findViewById(R.id.Review))
				.setVisibility(View.VISIBLE);

		((android.widget.Button) findViewById(R.id.Record))
				.setVisibility(View.VISIBLE);
		((android.widget.Button) findViewById(R.id.TakeSnapshot))
				.setVisibility(View.VISIBLE);
		((android.widget.Button) findViewById(R.id.Quit))
				.setVisibility(View.VISIBLE);
		((android.widget.Button) findViewById(R.id.SaveSnapshot))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.DiscardSnapshot))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.SkipSnapshot))
				.setVisibility(View.GONE);

		((android.widget.Button) findViewById(R.id.Stop))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.Play))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.Save))
				.setVisibility(View.GONE);
		((android.widget.Button) findViewById(R.id.Discard))
				.setVisibility(View.GONE);

		taggedFileName = ImageCaptureCallback.imageFileName;

		testProviders();
		Double latDouble = (Double) lat;
		String latString = latDouble.toString();
		Double lngDouble = (Double) lng;
		String lngString = lngDouble.toString();
		Double accDouble = (Double) acc;
		String accString = accDouble.toString();

		registerFilePrefs(taggedFileName, latString, lngString, accString, tags);
		// Request.notification( myContext
		// ,"hello","File:"+taggedFileName+"lat"+latString+"long"+lngString+"acc"+accString);
		tempToUserChoice();
		// tempToQueue();

	}

	public void upload_functionality() {

		if (!qUploader.isAlive()) {
			// Request.notification( myContext ,"hello","if");
			qUploader.start();
		}

	}

	public void testProviders() {
		List<String> providers = locationManager.getProviders(true);

		for (String provider : providers) {
			locationManager.requestLocationUpdates(provider, 1000, 0,
					new LocationListener() {
						public void onLocationChanged(Location location) {
						}

						public void onProviderDisabled(String provider) {
						}

						public void onProviderEnabled(String provider) {
						}

						public void onStatusChanged(String provider,
								int status, Bundle Extras) {
						}

					});

			Location location = locationManager.getLastKnownLocation(provider);

			if (location != null) {
				lat = location.getLatitude();
				lng = location.getLongitude();
				acc = location.getAccuracy();

			}
		}
	}

	public void registerFilePrefs(String filename, String latitude,
			String longitude, String accuracy, String tags) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);

		SharedPreferences.Editor editor = mySharedPreferences.edit();

		editor.putString(filename + "Latitude", latitude);
		editor.putString(filename + "Longitude", longitude);
		editor.putString(filename + "Accuracy", accuracy);
		editor.putString(filename + "Tags", tags);

		editor.commit();
	}

	public void tempToUserChoice() {
		File[] tempfiles;
		tempfiles = tempFolder.listFiles();

		// qUploader.setUploading(false);

		// associateJpegsWithWav();

		for (int i = 0; i < tempfiles.length; i++) {
			try {
				FileChannel channel = new RandomAccessFile(tempfiles[i], "rw")
						.getChannel();
				FileLock lock = channel.lock();

				try {
					lock = channel.tryLock();
				} catch (Exception e) {
				}

				tempfiles[i].renameTo(new File(userChoiceFolder
						.getAbsoluteFile()
						+ "/" + tempfiles[i].getName()));

				lock.release();
			} catch (Exception e) {
			}
		}
		// qUploader.setUploading(true);
	}

	public void tempToQueue() {
		File[] tempfiles;
		tempfiles = tempFolder.listFiles();

		qUploader.setUploading(false);

		// associateJpegsWithWav();

		for (int i = 0; i < tempfiles.length; i++) {
			try {
				FileChannel channel = new RandomAccessFile(tempfiles[i], "rw")
						.getChannel();
				FileLock lock = channel.lock();

				try {
					lock = channel.tryLock();
				} catch (Exception e) {
				}

				tempfiles[i].renameTo(new File(queueFolder.getAbsoluteFile()
						+ "/" + tempfiles[i].getName()));

				lock.release();
			} catch (Exception e) {
			}
		}
		qUploader.setUploading(true);
	}

	public void associateJpegsWithWav() {
		File[] tempfiles;
		tempfiles = tempFolder.listFiles();

		String wavfilename = "";

		for (int i = 0; i < tempfiles.length; i++) {
			String absfilename = tempfiles[i].getPath();
			String ext = absfilename.substring(
					absfilename.lastIndexOf(".") + 1, absfilename.length());

			if (ext.equals(new String("wav"))) {
				wavfilename = absfilename.substring(absfilename
						.lastIndexOf("/") + 1, absfilename.length());
				break;
			}
		}

		if (!wavfilename.equals(new String(""))) {
			for (int i = 0; i < tempfiles.length; i++) {
				String absfilename = tempfiles[i].getPath();
				String ext = absfilename.substring(
						absfilename.lastIndexOf(".") + 1, absfilename.length());

				if (ext.equals(new String("jpg"))) {
					String jpgfilename = absfilename
							.substring(absfilename.lastIndexOf("/") + 1,
									absfilename.lastIndexOf("."));

					int mode = Activity.MODE_PRIVATE;
					SharedPreferences mySharedPreferences = getSharedPreferences(
							"mySharedPreferences", mode);
					SharedPreferences.Editor editor = mySharedPreferences
							.edit();
					editor.putString(jpgfilename + "Wav", wavfilename);
					editor.commit();
				}
			}
		}
	}

	public void unregisterFilePrefs(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);

		SharedPreferences.Editor editor = mySharedPreferences.edit();
		editor.remove(filename + "Latitude");
		editor.remove(filename + "Longitude");
		editor.remove(filename + "Accuracy");
		editor.remove(filename + "Tags");
		editor.commit();
	}

	private Handler toastHandler = new Handler() {
		public void handleMessage(Message msg) {
			Bundle b = msg.getData();
			String msgString = b.getString("message");
			TextView tv = (TextView) findViewById(R.id.statusbar);
			tv.setVisibility(1);
			tv.setText(msgString);
			// Request.notification( myContext ,"Message",msgString);

		}
	};

	public Handler getHandler() {
		return this.toastHandler;
	}

	// @return fileLatitude
	public String getFileLatitude(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
				mode);
		return mySharedPreferences.getString(filename + "Latitude", "0.0");
	}

	// @return fileLongitude
	public String getFileLongitude(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
				mode);
		return mySharedPreferences.getString(filename + "Longitude", "0.0");
	}

	// @return fileAccuracy
	public String getFileAccuracy(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
				mode);
		return mySharedPreferences.getString(filename + "Accuracy", "0.0");
	}

	// @return fileTags
	public String getFileTags(String filename) {
		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);
		return mySharedPreferences.getString(filename + "Tags", "");
	}

	// @return username
	public String getUsername() {
		int mode = Activity.MODE_PRIVATE;

		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);
		return mySharedPreferences.getString("username", "");

	}

	// @return password
	public String getPassword() {

		int mode = Activity.MODE_PRIVATE;

		SharedPreferences mySharedPreferences = getSharedPreferences(
				"mySharedPreferences", mode);

		return mySharedPreferences.getString("password", "");
	}

	public String getFolderPath() {
		return this.folderPath;
	}

	// @return tempFolderPath
	public String getTempFolderPath() {
		return this.tempFolderPath;
	}

	public String getQueueFolderPath() {
		return this.queueFolderPath;
	}

}